package com.example.zjx8969.myapplication.database;

import androidx.sqlite.db.SupportSQLiteDatabase;
import androidx.room.Room;
import androidx.room.migration.Migration;
import androidx.annotation.NonNull;

import com.example.zjx8969.myapplication.App;

import java.io.File;
import java.util.Locale;

public class DataBaseHolder {
    private static DataBaseHolder holder;
    public AppDataBase database;
    public LocalRelativeDatabase localRelativeDatabase;

    private DataBaseHolder() {
        database = Room.databaseBuilder(App.getInstance(), AppDataBase.class, "database")
                .addMigrations(new Migration(1, 2) {
                    @Override
                    public void migrate(@NonNull SupportSQLiteDatabase database) {
                        database.execSQL("drop table user");
                    }
                })
                .addMigrations(new Migration(2, 3) {
                    @Override
                    public void migrate(@NonNull SupportSQLiteDatabase database) {
                        String sql = "CREATE TABLE IF NOT EXISTS `lookInfo` (`key` TEXT NOT NULL, `styleName` TEXT, `watermarkMsg` TEXT, `watermarkUrl` TEXT, `packageUrl` TEXT, `effectUrl` TEXT, `actionUrl` TEXT, `seeHowToIcon` TEXT, `eventName` TEXT, `tag1` TEXT, `tag2` TEXT, `tag3` TEXT, `name` TEXT, `kinUserId` TEXT, PRIMARY KEY(`key`))";
                        database.execSQL(sql);
                    }
                })
                .addMigrations(new Migration(3, 4) {
                    @Override
                    public void migrate(@NonNull SupportSQLiteDatabase database) {
                        String sql = "CREATE TABLE IF NOT EXISTS sdkControl (`key` TEXT NOT NULL, `state` INTEGER NOT NULL, `crashInfo` TEXT, `gdpr` TEXT, PRIMARY KEY(`key`))";
                        database.execSQL(sql);
                    }
                })
                .allowMainThreadQueries().build();

        switchDatabase();
    }

    public synchronized void switchDatabase() {
        if (localRelativeDatabase != null) {
            localRelativeDatabase.close();
        }
        String fileName = new File(App.getInstance().getFilesDir(), "/database/" + Locale.getDefault().getCountry() + "/local_database.db").getAbsolutePath();
        localRelativeDatabase = Room.databaseBuilder(App.getInstance(), LocalRelativeDatabase.class, fileName)
                .allowMainThreadQueries().build();

    }

    public static DataBaseHolder getInstance() {
        if (holder == null) {
            synchronized (DataBaseHolder.class) {
                if (holder == null) holder = new DataBaseHolder();
            }
        }
        return holder;
    }
}
